package switchviz.core.scenario;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;

import switchviz.Application;
import switchviz.core.ResourceManager;
import switchviz.core.view.ViewScenarioConfiguration;
import switchviz.gui.component.PaddingPanel;
import switchviz.network.netswitch.SwitchScenarioConfiguration;
import switchviz.recording.ReplayPanel;

public class ScenarioPanel extends PaddingPanel implements ActionListener, ItemListener, ComponentListener
{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6838550459959747325L;
	private static Logger logger  = Logger.getLogger(ScenarioPanel.class);

	private ViewScenarioConfiguration _viewpanel = null;
	private ReplayPanel _replaypanel = null;
	private JPanel _container = null;
	private SwitchScenarioConfiguration _switchpanel = null;
	private ScenarioSourcePanel _sourcepanel = null;
	private ScenarioDataModel _scenedm = null;
	private JButton _buttstart = null;
	
	public ScenarioPanel()
	{
		try 
		{
			initialize();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	public ScenarioDataModel getScenarioModel()
	{
		if(_scenedm == null)
			_scenedm = new ScenarioDataModel();
		return _scenedm;
	}
	
	private ScenarioSourcePanel getSourcePanel()
	{
		if(_sourcepanel == null)
		{
			try
			{
				_sourcepanel = new ScenarioSourcePanel();
				_sourcepanel.addItemListener(this);
			}
			catch(Exception e)
			{
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		}
		return _sourcepanel;
	}
	
	private ViewScenarioConfiguration getViewPanel() throws JDOMException, IOException
	{
		if(_viewpanel == null)
		{
			_viewpanel = new ViewScenarioConfiguration(getScenarioModel());
			_viewpanel.addItemListener(new ItemListener(){
				public void itemStateChanged(ItemEvent e) 
				{
					getSwitchPanel().setSelAliasList(null);
					getSwitchPanel().setViewAlias(_viewpanel.getAliasList());
				}
			});
			_viewpanel.checkInitViz();
		}
		return _viewpanel;
	}
	
	private SwitchScenarioConfiguration getSwitchPanel() 
	{
		if(_switchpanel == null)
		{
			_switchpanel = new SwitchScenarioConfiguration(getScenarioModel());
		}
		return _switchpanel;
	}
	
	private ReplayPanel getReplayPanel()
	{
		if(_replaypanel == null)
		{
			_replaypanel = new ReplayPanel();
		}
		return _replaypanel;
	}
	
	
	private void initialize() throws JDOMException, IOException
	{
		this.setLayout(ResourceManager.getInstance().getBorderLayout());
		_container = new JPanel();
	    _container.add(getSwitchPanel());
	    
	    _buttstart = new JButton("Start", ResourceManager.getInstance().getImageIconBioHazard());
		_buttstart.setActionCommand(ResourceManager.getInstance().getActionNew());
		_buttstart.addActionListener(this);
	    
		PaddingPanel contentpane = new PaddingPanel();
		contentpane.setLayout(new BoxLayout(contentpane, BoxLayout.PAGE_AXIS));
		contentpane.setBorder(BorderFactory.createLoweredBevelBorder());
		contentpane.add(getSourcePanel());
		contentpane.add(getViewPanel());
		contentpane.add(_container);
		
        JPanel buttonpanel = new JPanel();
        buttonpanel.setLayout(new BoxLayout(buttonpanel, BoxLayout.LINE_AXIS));
        buttonpanel.add(Box.createHorizontalGlue());
        buttonpanel.add(_buttstart);
		
		this.add(contentpane, BorderLayout.CENTER);
		this.add(buttonpanel, BorderLayout.SOUTH);
	    this.addComponentListener(this);
	}
	
	private void updateScenarioModel() throws JDOMException, IOException
	{
		getScenarioModel().setProcessSynchron(getSwitchPanel().getScenarioModel().isProcessSynchron());
		getScenarioModel().setRecord(getSwitchPanel().getScenarioModel().isRecord());
		getScenarioModel().setTimeintervall(getSwitchPanel().getScenarioModel().getTimeintervall());
		getScenarioModel().setRenderrate(getViewPanel().getScenarioModel().getRenderrate());
		getScenarioModel().setVisualize(getViewPanel().getScenarioModel().isVisualize());
	}

	public void actionPerformed(ActionEvent evt) 
	{
		String command = evt.getActionCommand();
		try
		{
			if(ResourceManager.getInstance().getActionNew().equals(command))
			{
		    	updateScenarioModel();
		    	if(getSourcePanel().isSwitchSelected())
		    	{
		    		if(getSourcePanel().isSwitchSelected() && getScenarioModel().isRecord())
		    		{
		    			if(getSwitchPanel().getRecordFile() == null)
		    			{
		    				JOptionPane.showMessageDialog(this,
			    				    "Please select the Record File and the designated Signals.",
			    				    "Form not complete!",
			    				    JOptionPane.WARNING_MESSAGE);
			    			return;
		    			}
		    			_buttstart.setEnabled(false);
		    			if(getScenarioModel().isVisualize())
		    			{
		    				new ScenarioLoader(Application.getInstance().getMainFrame(), getSourcePanel().getSwitchDataModel(), 
		    						getViewPanel().getViewDataModel(), getScenarioModel(), getSwitchPanel());
		    			}
		    			else
		    			{
		    				new ScenarioLoader(Application.getInstance().getMainFrame(), getSourcePanel().getSwitchDataModel(), 
		    						getScenarioModel(), getSwitchPanel());
		    			}
		    			_buttstart.setEnabled(true);
		    		}
		    		else
		    		{
		    			_buttstart.setEnabled(false);
		    			new ScenarioLoader(Application.getInstance().getMainFrame(), getSourcePanel().getSwitchDataModel(), 
						          getViewPanel().getViewDataModel(), getScenarioModel());
		    			_buttstart.setEnabled(true);
		    		}
		    	}
		    	else
		    	{
		    		_buttstart.setEnabled(false);
	    			new ScenarioLoader(Application.getInstance().getMainFrame(), getViewPanel().getViewDataModel(),
	    					getScenarioModel(), getSourcePanel().getRecord());
	    			_buttstart.setEnabled(true);
		    	}
			}
		}
		catch(Exception e)
		{
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}

	public void itemStateChanged(ItemEvent evt) 
	{
		if(evt.getSource().getClass().equals(JComboBox.class))
		{
			if(getSourcePanel().getRecord() != null)
				getReplayPanel().setRecordModel(getSourcePanel().getRecord());
			return;
		}
		try
		{
			getSourcePanel().reload();
			if(getSourcePanel().isSwitchSelected())
			{
				_container.removeAll();
				_container.add(getSwitchPanel());
				getSourcePanel().changeToViewMode();
				getViewPanel().changeVisualizeRecordState(false);
			}
			else
			{
				_container.removeAll();
				getSourcePanel().changeToRecordMode();
				_container.add(getReplayPanel());
				getViewPanel().changeVisualizeRecordState(true);
				if(getSourcePanel().getRecord() != null)
					getReplayPanel().setRecordModel(getSourcePanel().getRecord());
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		_container.validate();
		this.repaint();
	}

	public void componentShown(ComponentEvent evt) 
	{
		try
		{
			getSourcePanel().reload();
			getViewPanel().reload();
		}
		catch(Exception e)
		{
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void componentHidden(ComponentEvent arg0) {}
	public void componentMoved(ComponentEvent arg0) {}
	public void componentResized(ComponentEvent arg0) {}
}
